//
//  EXHTTPAgent.m
//  Edaox
//
//  Created by cao pan on 7/10/14.
//  Copyright (c) 2014 edaox. All rights reserved.
//

#import "EXHTTPAgent.h"
#import "EXRequestConfig.h"
#import "AFHTTPRequestOperation.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "EXRequestMessage.h"
#import "AFJSONRequestOperation.h"
#import "JSONKit.h"



@implementation EXHTTPAgent

static EXHTTPAgent *gSharedAgent = nil;


+ (EXHTTPAgent *)sharedAgent
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        gSharedAgent = [[EXHTTPAgent alloc] initWithBaseURL:[NSURL URLWithString:API_HOST_RELEASE]];
    });
    return gSharedAgent;
}

- (id)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }
    
    [self registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    [self setDefaultHeader:@"User-Agent" value:@"/iPhone-V_1.0."];
    [self setStringEncoding:NSUTF8StringEncoding];
    [self setDefaultHeader:@"Content-Type" value:@"text/html"];
    [self setParameterEncoding:AFJSONParameterEncoding];
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    return self;
}


- (void)requestUploadPicture:(EXRequestMessage *)requestMessage
               responseBlock:(EXResponseBlock)responseBlock
{
    NSData * imageData = requestMessage.pictureData;
    NSMutableURLRequest *request =  [self multipartFormRequestWithMethod:EX_REQUEST_METHOD_POST
                                     path:requestMessage.requestPath
                               parameters:requestMessage.requestBody
                constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                    [formData appendPartWithFileData:imageData
                                                name:@"imgFile"
                                            fileName:nil
                                            mimeType:@"image/jpeg"];
                }];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self requestSuccessed:responseObject responseMessage:responseBlock];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self requestFailed:error];
    
    }];
    [operation start];
}


- (void)requestAction:(EXRequestMessage *)requestMessage
      responseMessage:(EXResponseBlock)responseBlock
{
    NSString *requestPath = [NSString stringWithFormat:@"%@",[requestMessage requestPath]];
    NSDictionary *requestBody = [requestMessage requestBody];
    NSString *requestMethod = [requestMessage requestMethod];
    
    LOG(@"\n request path %@ \n request method %@ \n request body %@",requestPath,requestMethod,requestBody);
    
    
    if (requestMessage.isCryptParameters) {
        [requestMessage setString:requestPath forKey:@"api"];
 //       NSString * enStr = [AESCrypt encrptStr:[requestMessage requestBody]];
        [[requestMessage requestBody] removeAllObjects];
//        [requestMessage setString:enStr forKey:@"a"];
    }
    
    if ([requestMethod isEqualToString:EX_REQUEST_METHOD_GET]) {
        [[EXHTTPAgent sharedAgent]  getPath:requestPath
                                 parameters:requestBody
                                    success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [self requestSuccessed:responseObject responseMessage:responseBlock];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self requestFailed:error];
        }];
    }
    
    if ([requestMethod isEqualToString:EX_REQUEST_METHOD_POST]) {
        [[EXHTTPAgent sharedAgent]  postPath:requestPath
                                  parameters:requestBody
                                     success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                         [self requestSuccessed:responseObject responseMessage:responseBlock];
                                     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                         [self requestFailed:error];
                                     }];
    }
}


- (void)requestCancel:(EXRequestMessage *)requestMessage
{
    [self cancelAllHTTPOperationsWithMethod:requestMessage.requestMethod
                                       path:requestMessage.requestPath];
}



- (void)requestSuccessed:(id)responseObject
         responseMessage:(EXResponseBlock)responseBlock
{
    if (responseObject == nil) return;
    EXResponseMessage *responseMessage = [[EXResponseMessage alloc] init];
    [responseMessage parserResponseBody:responseObject];
    responseBlock(responseMessage);
    [[NSNotificationCenter defaultCenter] postNotificationName:NNKEY_NETWORK_REQUEST_FINISH object:nil];
}

- (void)requestFailed:(NSError *)error
{
#if EX_DEBUG
    NSString *errorStr = [NSString stringWithFormat:@"%@",error];
    Alert(@"提示",errorStr);
    LOG(@"error %@",error);
#else
    /*
    if ([[EXHTTPAgent sharedAgent] networkReachabilityStatus] == AFNetworkReachabilityStatusNotReachable) {
        Alert(@"提示", @"网络貌似链接不上,请稍后试试");
    }else{
        Alert(@"提示", @"服务器没有响应,请稍后试试");
    }*/
    
#endif
    [[NSNotificationCenter defaultCenter] postNotificationName:NNKEY_NETWORK_REQUEST_FINISH object:nil];
}


@end
